package com.git.smp.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import com.git.smp.controller.SmpUserController;
import com.git.smp.utils.JWTUtil;

@Service
public class LoginInterceptor implements HandlerInterceptor {
	Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	
	@Value("${jwt.password}")
	private String jwtPassword;
	
	@Value("${jwt.version}")
	private String version;

	/*
	 * @Override public void doFilter(ServletRequest request, ServletResponse
	 * response, FilterChain chain) throws IOException, ServletException {
	 * //logger.info(request.getLocalAddr());
	 * 
	 * HttpServletRequest httpRequest = (HttpServletRequest)request;
	 * logger.info(httpRequest.getRequestURI());
	 * 
	 * if("/index.html".equals(httpRequest.getRequestURI())||"/favicon.ico".equals(
	 * httpRequest.getRequestURI())||"/".equals(httpRequest.getRequestURI())||
	 * "/user/login".equals(httpRequest.getRequestURI())) { chain.doFilter(request,
	 * response); return; }
	 * 
	 * String accessToken = httpRequest.getHeader("accessToken");
	 * 
	 * if(JWTUtil.verify(accessToken, "smp@ahrcu")) { chain.doFilter(request,
	 * response); }else { //登录验证失败 //throw new SmpException("401", "令牌无效");
	 * response.getWriter().write("{\"code\":\"4001\",\"message\":\"\"}"); }
	 * 
	 * logger.info("登录拦截");
	 * 
	 * }
	 */

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		logger.info(httpRequest.getRequestURI());
		String accessToken = httpRequest.getHeader("accessToken");

		if (JWTUtil.verify(accessToken,jwtPassword,version)) {
			return true;
		} else {
			// 登录验证失败 //throw new SmpException("401", "令牌无效");
			response.getWriter().write("{\"code\":\"4001\",\"message\":\"\"}");
			return false;
		}
	}
}
